package com.all.play.myeventbus;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.all.play.myeventbus.bean.MessageEvent;
import com.all.play.myeventbus.bean.StickyEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SecondActivity extends AppCompatActivity {

    @BindView(R.id.btc)
    Button btc;
    @BindView(R.id.btd)
    Button btd;
    @BindView(R.id.tvb)
    TextView tvb;

    boolean isFirst = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        ButterKnife.bind(this);

        initView();
    }

    /*
    * 初始化view
    * */
    private void initView() {
        tvb.setText("第二个页面-->接收数据的显示");
    }

    //接收粘性事件
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void StickEventBus(StickyEvent se) {
        tvb.setText(se.msg);
    }



    @OnClick({R.id.btc, R.id.btd})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btc:
                EventBus.getDefault().post(new MessageEvent("Husky"));
                finish();
                break;
            case R.id.btd:
                //注册
                if (isFirst) {
                    isFirst = false;
                    EventBus.getDefault().register(SecondActivity.this);

                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().removeAllStickyEvents();
        EventBus.getDefault().unregister(SecondActivity.this);
    }
}
